<template>
  <el-form :model="form" label-width="120px" style="width: 400px">
    <el-form-item label="link">
      <el-input v-model="form.link" />
    </el-form-item>
    <el-form-item label="alt">
      <el-input v-model="form.alt" />
    </el-form-item>
    <el-form-item label="图片上传">
      <input type="file" @change="upload" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit">添加</el-button>
    </el-form-item>
  </el-form>

  <img :src="form.img" alt="" />
</template>

<script lang="ts" setup>
import { reactive } from "vue";
import { bannerAddApi } from "@/api/banner";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";

// do not use same name with ref
const form = reactive({
  link: "",
  alt: "",
  img: "",
});

const upload = (event: any) => {
  // event.target.files[0]表示input上传的文件信息
  // console.log(event.target.files[0]);

  // 要将图片转成base64
  const render = new FileReader();
  render.readAsDataURL(event.target.files[0]);
  render.onload = (e: any) => {
    form.img = e.target.result;
  };
};

const router = useRouter();
const onSubmit = async () => {
  // console.log(form);
  const res = await bannerAddApi(form);
  ElMessage.success("轮播图新增成功");
  router.push("/banner/list");
};
</script>
